package main

import (
	"github.com/lxn/walk"
	"sync"
)

type MainWind struct {
	*walk.MainWindow
	sync.RWMutex
	model           *EnvModel
	op              *walk.Composite
	lb              *walk.ListBox        // 连接列表
	slb             *walk.ListBox        // 订阅主题列表
	outTE           *walk.TextEdit       // 日志输出
	pubRec          PubRec               // 发布接收
	sub             map[string]*EnvModel // 和下面的conn的key是同一个，不同连接的隔离
	conn            map[string]*Animals
	curAnimals      string // 当前操作的collection，是上面conn和sub的key
	curSub          int    // 当前操作的订阅索引
	curAnimalsLabel *walk.Label
}
type PubRec struct {
	Msg        *walk.TextEdit // 输出
	DataBinder *walk.DataBinder

	PubContentType string
	PubQoS         int
	PubRetain      bool
	PubTopic       string
	PubPayload     string
	PubBody        string
}
type Sub struct {
	Topic string
	Qos   int
	Alias int
}

func NewMainWind() *MainWind {
	return &MainWind{
		conn:   make(map[string]*Animals),
		sub:    make(map[string]*EnvModel),
		curSub: -1,
		model:  NewEnvModel(),
		pubRec: PubRec{PubQoS: 0, PubContentType: "Plaintext", PubPayload: "JSON", PubRetain: false},
	}
}

// AddAnimals 添加新连接
func (m *MainWind) AddAnimals(animals *Animals) bool {
	m.Lock()
	defer m.Unlock()
	if _, ok := m.conn[animals.Name]; ok {
		return ok
	}
	m.conn[animals.Name] = animals
	return true
}

// GetCurAnimals 获取当前连接信息
func (m *MainWind) GetCurAnimals() *Animals {
	m.RLock()
	defer m.RUnlock()
	return m.conn[m.curAnimals]
}

// Select 选择连接
func (m *MainWind) Select(name string) {
	m.curAnimals = name
	if len(name) > 7 {
		name = name[:7] + "..."
	}
	m.curAnimalsLabel.SetText(name)
}
